package com.zbkj.crmeb.merchant.admin.controller;

import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.express.vo.LogisticsResultVo;
import com.zbkj.crmeb.merchant.admin.service.MerStoreOrderService;
import com.zbkj.crmeb.merchant.api.request.UpdatePickingProductRequest;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.request.*;
import com.zbkj.crmeb.store.response.DataAnalysisResponse;
import com.zbkj.crmeb.store.response.OrderNumberResponse;
import com.zbkj.crmeb.store.response.StoreOrderInfoResponse;
import com.zbkj.crmeb.store.response.StoreOrderResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;


/**
 * 订单表 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("api/admin/mer/store/order")
@Api(tags = "订单") //配合swagger使用

public class MerStoreOrderController extends AdminBaseController {

    @Autowired
    private MerStoreOrderService storeOrderService;

    /**
     * 分页显示订单表
     * @param request 搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "分页列表") //配合swagger使用
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<StoreOrderResponse>  getList(
            @Validated StoreOrderSearchRequest request,
            @Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest){
        request.setMerId(getMerId(servletRequest));
        request.setIsPicking(false);
        return CommonResult.success(storeOrderService.getAdminList(request, pageParamRequest));
    }

    @ApiOperation(value = "分页列表") //配合swagger使用
    @RequestMapping(value = "/picking/list", method = RequestMethod.GET)
    public CommonResult<StoreOrderResponse>  getPickingList(
            @Validated StoreOrderSearchRequest request,
            @Validated PageParamRequest pageParamRequest, HttpServletRequest servletRequest){
        request.setMerId(getMerId(servletRequest));
        request.setIsPicking(true);
        return CommonResult.success(storeOrderService.getPickingList(request, pageParamRequest));
    }


    /**
     * 删除订单表
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public CommonResult<String> delete(@RequestParam(value = "id") Integer id){
        StoreOrder storeOrder = storeOrderService.getById(id);
        if(!OrderStatusEnum.CANCEL.getCode().equals(storeOrder.getStatus())){
            return CommonResult.failed("删除失败，只允许删除已取消的订单！");
        }
        if(storeOrder.getIsDel()||storeOrder.getIsSystemDel()){
            return CommonResult.failed("此订单已经被删除了！");
        }
        storeOrder.setIsSystemDel(true);
        if(storeOrderService.updateById(storeOrder)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 备注订单
     * @param id integer id
     * @param mark String 备注
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "备注")
    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    public CommonResult<String> mark(@RequestParam Integer id, @RequestParam String mark){
        if(storeOrderService.mark(id, mark)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 修改订单表
     * @param id integer id
     * @param request String 备注
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "修改订单")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult<String> update(@RequestParam Integer id, @RequestBody @Validated StoreOrderRequest request){
        StoreOrder storeOrder = new StoreOrder();
        BeanUtils.copyProperties(request, storeOrder);
        storeOrder.setId(id);
        //修改订单后,微信支付需重新生成订单号
        storeOrder.setOrderId(CrmebUtil.getOrderNo(Constants.PAY_TYPE_WE_CHAT));
        if(storeOrderService.updateById(storeOrder)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    /**
     * 查询订单表信息
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<StoreOrderInfoResponse> info(@RequestParam(value = "id") Integer id){
        return CommonResult.success(storeOrderService.info(id));
    }

    /**
     * 发货
     * @param request StoreOrderSendRequest 发货参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "发送货")
    @RequestMapping(value = "/send", method = RequestMethod.GET)
    public CommonResult<Boolean> send(@Validated StoreOrderSendRequest request){
        if(!request.getType().equals("3") && !request.getName().equals("同城配送")){
            if(StringUtils.isBlank(request.getExpressId())){
                throw new CrmebException("请选择快递公司/填写收货人");
            }

            if(StringUtils.isBlank(request.getExpressCode())){
                throw new CrmebException("请填写快递单号/收货人手机号码");
            }
        }

        return CommonResult.success(storeOrderService.send(request));
    }

    /**
     * 退款
     * @param request StoreOrderRefundRequest 退款参数
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "退款")
    @RequestMapping(value = "/refund", method = RequestMethod.GET)
    public CommonResult<Boolean> send(@Validated StoreOrderRefundRequest request){
        return CommonResult.success(storeOrderService.refund(request));
//        return storeOrderService.refund(request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "退货退款")
    @PostMapping(value = "/refund/goods")
    public CommonResult<Boolean> refundGoods(@Validated RefundGoodsRequest request){
        return CommonResult.success(storeOrderService.refundGoods(request));
    }

    /**
     * 退款
     * @param id Integer 订单id
     * @param reason String 原因
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @ApiOperation(value = "拒绝退款")
    @RequestMapping(value = "/refund/refuse", method = RequestMethod.GET)
    public CommonResult<Boolean> refundRefuse(@RequestParam Integer id, @RequestParam String reason){
//        if(StringUtils.isBlank(reason)){
//            CommonResult.validateFailed("请填写退款原因");
//        }
        return CommonResult.success(storeOrderService.refundRefuse(id, reason));
    }

    /**
     * 快递查询
     * @param id Integer 订单id
     * @author Mr.Zhang
     * @since 2020-07-06
     */
    @ApiOperation(value = "快递查询")
    @RequestMapping(value = "/getLogisticsInfo", method = RequestMethod.GET)
    public CommonResult<LogisticsResultVo> getLogisticsInfo(@RequestParam(value = "id") Integer id){
        return CommonResult.success(storeOrderService.getLogisticsInfo(id));
    }

    @ApiOperation(value = "子订单确认订单")
    @PutMapping(value = "/confirmChildOrder")
    public CommonResult<Object> confirmChildOrder(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id
            ,@ApiParam(value = "管理员备注", required = true) @RequestParam(value = "remark") String remark){
        return storeOrderService.confirmChildOrder(id,remark) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "修改用户地址")
    @PutMapping(value = "/updateUserAddress")
    public CommonResult<Object> updateUserAddress(@RequestBody @Validated UpdateUserAddressRequest request){
        return storeOrderService.updateUserAddress(request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "修改订单商品成交价")
    @PutMapping(value = "/updateOrderPrice")
    public CommonResult<Object> updateOrderPrice(@RequestParam @ApiParam(value = "子订单id", required = true)Integer id,
                                                 @RequestParam @ApiParam(value = "实际支付价格", required = true) BigDecimal price){
        return CommonResult.success(storeOrderService.updateOrderPrice(id,price));
    }

    @ApiOperation(value = "取消订单")
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public CommonResult<Boolean> cancel(@RequestParam(value = "id") Integer id){
        return storeOrderService.cancel(id) ?CommonResult.success() :  CommonResult.failed();
    }

    @ApiOperation(value = "核对校验码")
    @RequestMapping(value = "/code/check", method = RequestMethod.POST)
    public CommonResult<Boolean> checkCode(@RequestParam @ApiParam(value = "子订单id", required = true) Integer id,
                                           @RequestParam @ApiParam(value = "校验码", required = true) String verifyCode){
        return storeOrderService.checkCode(id,verifyCode) ?CommonResult.success() :  CommonResult.failed();
    }

    @ApiOperation(value = "扣除可用余额")
    @RequestMapping(value = "/account/deduct", method = RequestMethod.POST)
    public CommonResult<Boolean> deductAccount(@RequestParam @ApiParam(value = "总订单id", required = true) Integer id, HttpServletRequest servletRequest){
        return storeOrderService.deductAccount(id,getMerId(servletRequest)) ?CommonResult.success() :  CommonResult.failed();
    }

    @ApiOperation(value = "获取商家小程序首页订单数量")
    @GetMapping(value = "/getOrderNumber")
    public CommonResult<List<OrderNumberResponse>> getOrderNumber(HttpServletRequest servletRequest){
        return CommonResult.success(storeOrderService.getOrderNumber(getMerId(servletRequest)));
    }

    @ApiOperation(value = "数据分析")
    @GetMapping(value = "/data/analysis")
    public CommonResult<List<DataAnalysisResponse>> dataAnalysis(PageParamRequest pageParamRequest,HttpServletRequest servletRequest){
        return CommonResult.success(storeOrderService.dataAnalysis(getMerId(servletRequest),pageParamRequest));
    }

    @ApiOperation(value = "商户确认完成子订单")
    @PutMapping(value = "/confirm/receipt")
    public CommonResult<Object> confirmReceiptOrder(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id,
                                                   @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark){
        return storeOrderService.confirmReceiptOrder(id, remark) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "使用平台物流")
    @PostMapping(value = "/use/sysDelivery")
    public CommonResult<Boolean> useSystemDelivery(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id){
        return CommonResult.success(storeOrderService.useSystemDelivery(id));
    }

    @ApiOperation(value = "商户后台备注")
    @PostMapping(value = "/note")
    public CommonResult<String> note(@ApiParam(value = "子订单id", required = true)@RequestParam Integer id, @RequestParam String note){
        return storeOrderService.note(id, note) ? CommonResult.success():CommonResult.failed();
    }

    @ApiOperation(value = "云仓商品订单自主发货")
    @PutMapping(value = "/independent/delivery")
    public CommonResult<Object> independentDelivery(@ApiParam(value = "子订单id", required = true) @RequestParam(value = "id") Integer id,
                                                    @ApiParam(value = "false平台发货  true自行发货", required = true) @RequestParam(value = "type") boolean type,
                                                    HttpServletRequest servletRequest){
        return storeOrderService.independentDelivery(id,type,getMerId(servletRequest),CrmebUtil.getClientIp(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "确认线下付款")
    @PutMapping(value = "/confirm/offline")
    public CommonResult<Object> offlineConfirm(@ApiParam(value = "主订单id", required = true) @RequestParam(value = "id") Integer id,
                                                @ApiParam(value = "false  true确认", required = true) @RequestParam(value = "type") boolean type,
                                                @ApiParam(value = "收款凭证", required = true) @RequestParam(value = "receiptVoucher") String receiptVoucher,
                                                HttpServletRequest servletRequest){
        return storeOrderService.offlineConfirm(id,type,receiptVoucher,getMerId(servletRequest),CrmebUtil.getClientIp(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "修改待核实批采订单商品数量")
    @PutMapping(value = "/picking/product/update")
    public CommonResult<Object> updatePickingProduct(@Validated @RequestBody UpdatePickingProductRequest request) {
        return storeOrderService.updatePickingProduct(request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "支付人年度限额")
    @PutMapping(value = "/check/annual/limit")
    public CommonResult<String> annualLimit(@RequestParam List<String> annualLimit) {
        return storeOrderService.annualLimit(annualLimit);
    }


}



